<?php
/**
 * 联系表单组件
 * 所有文本信息完全通过$data配置，无任何硬编码
 */
$configKey = isset($configKey) ? $configKey : 'contact_form';

// 默认配置（所有文本集中配置）
$defaultConfig = [
    'section_id' => $configKey,
    'section_pretitle' => '', // 可留空
    'section_title' => '发送消息给我们',
    'section_subtitle' => '无论您有任何问题或需求，我们都会尽快与您联系',
    
    // 表单基础配置
    'form' => [
        'action' => '/submit-contact.php',
        'method' => 'post',
        'id' => $configKey . '-form',
        'novalidate' => true
    ],
    
    // 所有文本配置（集中管理所有展示文本）
    'texts' => [
        'success_message' => '您的消息已成功发送，我们将尽快与您联系！',
        'error_message' => '提交过程中出现错误，请稍后再试',
        'submit_text' => '发送消息',
        'submit_loading_text' => '发送中...',
        'privacy_note' => '提交即表示您同意我们的隐私政策，我们会保护您的个人信息',
        'required_mark' => '*',
        'privacy_link_text' => '隐私政策',
        'form_group_error' => '此字段无效',
        'required_field_error' => '此字段为必填项',
        'max_length_error' => '最多可输入{max}个字符',
        'network_error_message' => '网络连接错误，请检查您的网络后重试' // 新增：网络错误提示
    ],
    
    // 样式配置
    'style' => [
        'form_field_border' => 'border-gray-300',
        'form_field_focus_ring' => 'ring-blue-500'
    ],
    
    // 交互配置
    'interaction' => [
        'real_time_validation' => true,
        'scroll_to_error' => true,
        'reset_form_after_success' => true,
        'loading_indicator' => true
    ],
    
    // 表单字段配置
    'fields' => [
        [
            'name' => 'name',
            'label' => '您的姓名',
            'type' => 'text',
            'required' => true,
            'placeholder' => '请输入您的姓名',
            'validation' => [
                'min_length' => 2,
                'max_length' => 50,
                'error_message' => '请输入至少2个字符的姓名'
            ]
        ],
        [
            'name' => 'email',
            'label' => '电子邮箱',
            'type' => 'email',
            'required' => true,
            'placeholder' => '请输入您的邮箱地址',
            'validation' => [
                'pattern' => '/^[^\s@]+@[^\s@]+\.[^\s@]+$/',
                'error_message' => '请输入有效的邮箱地址'
            ]
        ],
        [
            'name' => 'phone',
            'label' => '联系电话',
            'type' => 'tel',
            'required' => false,
            'placeholder' => '请输入您的联系电话（选填）',
            'validation' => [
                'pattern' => '/^1[3-9]\d{9}$/',
                'error_message' => '请输入有效的手机号码'
            ]
        ],
        [
            'name' => 'subject',
            'label' => '咨询主题',
            'type' => 'select',
            'required' => true,
            'options' => [
                '' => '请选择咨询主题',
                'service' => '服务咨询',
                'price' => '价格咨询',
                'support' => '技术支持',
                'other' => '其他问题'
            ],
            'validation' => [
                'error_message' => '请选择咨询主题'
            ]
        ],
        [
            'name' => 'message',
            'label' => '咨询内容',
            'type' => 'textarea',
            'required' => true,
            'placeholder' => '请详细描述您的需求或问题',
            'rows' => 5,
            'validation' => [
                'min_length' => 10,
                'max_length' => 2000,
                'error_message' => '请输入至少10个字符的咨询内容'
            ]
        ],
        [
            'name' => 'privacy_accept',
            'label' => '我已阅读并同意{privacy_link}',
            'type' => 'checkbox',
            'required' => true,
            'validation' => [
                'error_message' => '您必须同意我们的隐私政策才能提交'
            ]
        ]
    ],
    
    'features' => [
        ['icon' => 'fa fa-globe', 'title' => '项目评估', 'subtitle' => '免费需求分析和项目评估'],
        ['icon' => 'fa fa-tags', 'title' => '透明的定价', 'subtitle' => '透明的开发成本与时间预估，避免项目超支与延期'],
        ['icon' => 'fa fa-users', 'title' => '专业团队', 'subtitle' => '专业团队全程一对一服务'],
        ['icon' => 'fa fa-calculator', 'title' => '实施路线', 'subtitle' => '详细的项目规划与实施步骤，确保开发过程顺利高效']
    ],
    
    'buttons' => [
        [
            'text' => '电话咨询',
            'icon' => 'fa fa-phone',
            'class' => 'px-6 py-3 bg-white/20 text-white rounded-lg font-medium hover:bg-white/30 transition-colors duration-300 flex items-center',
            'action' => 'tel:+1234567890'
        ],
        [
            'text' => '在线客服',
            'icon' => 'fa fa-comments',
            'class' => 'px-6 py-3 bg-white text-gray-700 rounded-lg font-medium hover:bg-gray-50 transition-colors duration-300 flex items-center',
            'action' => '#'
        ]
    ],
    
    'privacy' => [
        'link' => '/privacy.php',
        'link_target' => '_blank'
    ]
];

// 合并配置
$customConfig = $pageConfig['components']['contact_form'] ?? [];
$data = array_merge($defaultConfig, $customConfig);

// 处理样式类
$formFieldBaseClasses = "w-full px-4 py-3 rounded-lg border transition-all duration-300";
$formFieldClass = "{$formFieldBaseClasses} {$data['style']['form_field_border']} focus:outline-none focus:ring-2 focus:{$data['style']['form_field_focus_ring']} focus:border-transparent";
$submitBtnBaseClasses = "w-full font-semibold py-4 px-6 rounded-lg transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 border-2 border-blue-500 text-blue-500";
$submitBtnClass = "{$submitBtnBaseClasses}";
$errorFieldClass = "border-red-500";
$errorTextClass = "text-red-500 text-sm mb-2";

// 处理隐私政策链接
$privacyLinkHtml = sprintf(
    '<a href="%s" class="text-blue-600 hover:underline" target="%s">%s</a>',
    htmlspecialchars($data['privacy']['link']),
    htmlspecialchars($data['privacy']['link_target']),
    htmlspecialchars($data['texts']['privacy_link_text'])
);
foreach ($data['fields'] as &$field) {
    if (strpos($field['label'], '{privacy_link}') !== false) {
        $field['label'] = str_replace('{privacy_link}', $privacyLinkHtml, $field['label']);
    }
}
unset($field);
?>

<!-- 开发咨询表单组件 -->
<div id="<?php echo htmlspecialchars($data['section_id']); ?>" class="max-w-4xl mx-auto rounded-2xl overflow-hidden">
    <div class="grid grid-cols-1 lg:grid-cols-2">
        <!-- 左侧信息面板 -->
        <div class="p-8 lg:p-12 border border-gray-200">
            <?php if (!empty($data['section_pretitle'])): ?>
                <span class="inline-block text-sm font-semibold uppercase tracking-wider mb-2 opacity-90">
                    <?php echo htmlspecialchars($data['section_pretitle']); ?>
                </span>
            <?php endif; ?>
            
            <h2 class="text-3xl font-bold mb-4">
                <?php echo htmlspecialchars($data['section_title']); ?>
            </h2>
            <p class="mb-8 opacity-90">
                <?php echo htmlspecialchars($data['section_subtitle']); ?>
            </p>
            
            <?php if (!empty($data['features'])): ?>
                <div class="space-y-6">
                    <?php foreach($data['features'] as $item): ?>
                        <div class="flex items-start">
                            <div class="flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center border-2 border-gray-200">
                                <i class="fa <?php echo htmlspecialchars($item['icon']); ?>"></i>
                            </div>
                            <div class="ml-4">
                                <h4 class="font-semibold mb-1"><?php echo htmlspecialchars($item['title']); ?></h4>
                                <p class="text-sm opacity-80"><?php echo htmlspecialchars($item['subtitle']); ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($data['buttons'])): ?>
                <div class="flex flex-wrap gap-4 mt-12">
                    <?php foreach ($data['buttons'] as $button): ?>
                        <a 
                            href="<?php echo htmlspecialchars($button['action']); ?>" 
                            class="<?php echo htmlspecialchars($button['class']); ?>"
                            <?php if (strpos($button['action'], 'http') === 0): ?>target="_blank"<?php endif; ?>
                        >
                            <?php if (!empty($button['icon'])): ?>
                                <i class="fa <?php echo htmlspecialchars($button['icon']); ?> mr-2"></i>
                            <?php endif; ?>
                            <?php echo htmlspecialchars($button['text']); ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- 右侧表单面板 -->
        <div class="p-8 lg:p-12 bg-white">
            <div id="<?php echo $data['form']['id']; ?>-success" class="hidden mb-6 p-4 bg-green-50 border border-green-200 rounded-lg text-green-800">
                <div class="flex">
                    <i class="fa fa-check-circle text-green-500 mt-0.5 mr-3"></i>
                    <span><?php echo htmlspecialchars($data['texts']['success_message']); ?></span>
                </div>
            </div>
            
            <div id="<?php echo $data['form']['id']; ?>-error" class="hidden mb-6 p-4 bg-red-50 border border-red-200 rounded-lg text-red-800">
                <div class="flex">
                    <i class="fa fa-exclamation-circle text-red-500 mt-0.5 mr-3"></i>
                    <span id="<?php echo $data['form']['id']; ?>-error-text"><?php echo htmlspecialchars($data['texts']['error_message']); ?></span>
                </div>
            </div>
            
            <form 
                action="<?php echo htmlspecialchars($data['form']['action']); ?>" 
                method="<?php echo htmlspecialchars($data['form']['method']); ?>"
                class="space-y-6"
                id="<?php echo htmlspecialchars($data['form']['id']); ?>"
                <?php echo $data['form']['novalidate'] ? 'novalidate' : ''; ?>
            >
                <?php foreach ($data['fields'] as $field): ?>
                    <div class="form-group">
                        <?php if ($field['type'] !== 'checkbox'): ?>
                            <label 
                                for="<?php echo htmlspecialchars($field['name']); ?>" 
                                class="block text-gray-700 font-medium mb-2"
                            >
                                <?php echo htmlspecialchars($field['label']); ?>
                                <?php if ($field['required']): ?>
                                    <span class="<?php echo $errorTextClass; ?>"><?php echo htmlspecialchars($data['texts']['required_mark']); ?></span>
                                <?php endif; ?>
                            </label>
                        <?php endif; ?>
                        
                        <div class="<?php echo $errorTextClass; ?> hidden" data-error-for="<?php echo htmlspecialchars($field['name']); ?>"></div>
                        
                        <?php if ($field['type'] === 'textarea'): ?>
                            <textarea 
                                id="<?php echo htmlspecialchars($field['name']); ?>"
                                name="<?php echo htmlspecialchars($field['name']); ?>"
                                rows="<?php echo $field['rows'] ?? 4; ?>"
                                placeholder="<?php echo htmlspecialchars($field['placeholder'] ?? ''); ?>"
                                <?php echo $field['required'] ? 'required' : ''; ?>
                                data-validation="<?php echo htmlspecialchars(json_encode($field['validation'] ?? [])); ?>"
                                class="<?php echo $formFieldClass; ?>"
                            ></textarea>
                            
                        <?php elseif ($field['type'] === 'select'): ?>
                            <div class="relative">
                                <select 
                                    id="<?php echo htmlspecialchars($field['name']); ?>"
                                    name="<?php echo htmlspecialchars($field['name']); ?>"
                                    <?php echo $field['required'] ? 'required' : ''; ?>
                                    data-validation="<?php echo htmlspecialchars(json_encode($field['validation'] ?? [])); ?>"
                                    class="<?php echo $formFieldClass; ?> appearance-none"
                                >
                                    <?php foreach ($field['options'] as $value => $label): ?>
                                        <option value="<?php echo htmlspecialchars($value); ?>"><?php echo htmlspecialchars($label); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-500">
                                    <i class="fa fa-chevron-down"></i>
                                </div>
                            </div>
                            
                        <?php elseif ($field['type'] === 'checkbox'): ?>
                            <div class="flex items-start p-4 rounded-lg border <?php echo $data['style']['form_field_border']; ?> hover:border-blue-300 transition-colors duration-300">
                                <div class="flex items-center h-5">
                                    <input 
                                        id="<?php echo htmlspecialchars($field['name']); ?>"
                                        name="<?php echo htmlspecialchars($field['name']); ?>"
                                        type="checkbox"
                                        <?php echo $field['required'] ? 'required' : ''; ?>
                                        data-validation="<?php echo htmlspecialchars(json_encode($field['validation'] ?? [])); ?>"
                                        class="w-5 h-5 text-<?php echo $data['style']['form_field_focus_ring']; ?> focus:ring-<?php echo $data['style']['form_field_focus_ring']; ?> border-gray-300 rounded"
                                    >
                                </div>
                                <div class="ml-3 text-sm">
                                    <label 
                                        for="<?php echo htmlspecialchars($field['name']); ?>" 
                                        class="text-gray-700"
                                    >
                                        <?php echo $field['label']; ?>
                                        <?php if ($field['required']): ?>
                                            <span class="<?php echo $errorTextClass; ?>"><?php echo htmlspecialchars($data['texts']['required_mark']); ?></span>
                                        <?php endif; ?>
                                    </label>
                                </div>
                            </div>
                            
                        <?php else: ?>
                            <input 
                                type="<?php echo htmlspecialchars($field['type']); ?>"
                                id="<?php echo htmlspecialchars($field['name']); ?>"
                                name="<?php echo htmlspecialchars($field['name']); ?>"
                                placeholder="<?php echo htmlspecialchars($field['placeholder'] ?? ''); ?>"
                                <?php echo $field['required'] ? 'required' : ''; ?>
                                data-validation="<?php echo htmlspecialchars(json_encode($field['validation'] ?? [])); ?>"
                                class="<?php echo $formFieldClass; ?>"
                            >
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
                
                <?php 
                $hasPrivacyCheckbox = false;
                foreach ($data['fields'] as $field) {
                    if ($field['name'] === 'privacy_accept' && $field['type'] === 'checkbox') {
                        $hasPrivacyCheckbox = true;
                        break;
                    }
                }
                if (!empty($data['texts']['privacy_note']) && !$hasPrivacyCheckbox): 
                ?>
                    <div class="text-sm text-gray-600 mb-6 p-4 bg-gray-50 rounded-lg">
                        <i class="fa fa-shield-alt text-gray-400 mr-2"></i>
                        <?php echo htmlspecialchars($data['texts']['privacy_note']); ?>
                        <?php if (!empty($data['privacy']['link'])): ?>
                            <a 
                                href="<?php echo htmlspecialchars($data['privacy']['link']); ?>" 
                                class="text-blue-600 hover:underline ml-1"
                                target="<?php echo htmlspecialchars($data['privacy']['link_target']); ?>"
                            >
                                <?php echo htmlspecialchars($data['texts']['privacy_link_text']); ?>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                
                <div class="pt-4">
                    <button 
                        type="submit" 
                        class="<?php echo $submitBtnClass; ?>"
                        id="<?php echo $data['form']['id']; ?>-submit"
                    >
                        <span id="<?php echo $data['form']['id']; ?>-submit-text"><?php echo htmlspecialchars($data['texts']['submit_text']); ?></span>
                        <i class="fa fa-paper-plane ml-2"></i>
                        <?php if ($data['interaction']['loading_indicator']): ?>
                            <div id="<?php echo $data['form']['id']; ?>-loading" class="ml-2 hidden">
                                <i class="fa fa-spinner fa-spin"></i>
                            </div>
                        <?php endif; ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 表单交互脚本 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const formConfig = {
        formId: <?php echo json_encode($data['form']['id']); ?>,
        realTimeValidation: <?php echo $data['interaction']['real_time_validation'] ? 'true' : 'false'; ?>,
        scrollToError: <?php echo $data['interaction']['scroll_to_error'] ? 'true' : 'false'; ?>,
        resetFormAfterSuccess: <?php echo $data['interaction']['reset_form_after_success'] ? 'true' : 'false'; ?>,
        loadingIndicator: <?php echo $data['interaction']['loading_indicator'] ? 'true' : 'false'; ?>,
        // 所有文本均从$data获取
        submitLoadingText: <?php echo json_encode($data['texts']['submit_loading_text']); ?>,
        submitText: <?php echo json_encode($data['texts']['submit_text']); ?>,
        defaultFieldError: <?php echo json_encode($data['texts']['form_group_error']); ?>,
        requiredFieldError: <?php echo json_encode($data['texts']['required_field_error']); ?>,
        maxLengthError: <?php echo json_encode($data['texts']['max_length_error']); ?>,
        successMessage: <?php echo json_encode($data['texts']['success_message']); ?>,
        errorMessage: <?php echo json_encode($data['texts']['error_message']); ?>,
        networkErrorMessage: <?php echo json_encode($data['texts']['network_error_message']); ?>
    };

    const form = document.getElementById(formConfig.formId);
    if (!form) return;
    
    const submitButton = document.getElementById(`${formConfig.formId}-submit`);
    const submitText = document.getElementById(`${formConfig.formId}-submit-text`);
    const loadingIndicator = formConfig.loadingIndicator ? document.getElementById(`${formConfig.formId}-loading`) : null;
    const successMessage = document.getElementById(`${formConfig.formId}-success`);
    const errorMessage = document.getElementById(`${formConfig.formId}-error`);
    const errorMessageText = document.getElementById(`${formConfig.formId}-error-text`);

    // 重置表单状态
    function resetFormState() {
        if (successMessage) successMessage.classList.add('hidden');
        if (errorMessage) errorMessage.classList.add('hidden');
        
        form.querySelectorAll('.form-group').forEach(group => {
            const input = group.querySelector('input, textarea, select');
            const errorEl = group.querySelector(`[data-error-for="${input?.name}"]`);
            
            if (input) input.classList.remove('<?php echo $errorFieldClass; ?>');
            if (errorEl) {
                errorEl.textContent = '';
                errorEl.classList.add('hidden');
            }
        });
    }

    // 显示字段错误
    function showFieldError(field, message) {
        const formGroup = field.closest('.form-group');
        const errorEl = formGroup.querySelector(`[data-error-for="${field.name}"]`);
        
        field.classList.add('<?php echo $errorFieldClass; ?>');
        
        if (errorEl) {
            errorEl.textContent = message;
            errorEl.classList.remove('hidden');
        }
    }

    // 清除字段错误
    function clearFieldError(field) {
        const formGroup = field.closest('.form-group');
        const errorEl = formGroup.querySelector(`[data-error-for="${field.name}"]`);
        
        field.classList.remove('<?php echo $errorFieldClass; ?>');
        
        if (errorEl) {
            errorEl.textContent = '';
            errorEl.classList.add('hidden');
        }
    }

    // 验证单个字段
    function validateField(field) {
        const validation = field.dataset.validation ? JSON.parse(field.dataset.validation) : {};
        const value = field.type === 'checkbox' ? field.checked : (field.value || '').trim();
        let isValid = true;
        let errorMsg = validation.error_message || formConfig.defaultFieldError;

        // 所有验证提示均来自配置
        if (field.required && !value) {
            isValid = false;
            errorMsg = formConfig.requiredFieldError;
        }
        else if (validation.min_length && value.length < validation.min_length) {
            isValid = false;
        }
        else if (validation.max_length && value.length > validation.max_length) {
            isValid = false;
            errorMsg = formConfig.maxLengthError.replace('{max}', validation.max_length);
        }
        else if (validation.pattern && value && !new RegExp(validation.pattern).test(value)) {
            isValid = false;
        }

        if (isValid) {
            clearFieldError(field);
        } else {
            showFieldError(field, errorMsg);
        }

        return isValid;
    }

    // 验证整个表单
    function validateForm() {
        let isFormValid = true;
        const fields = form.querySelectorAll('input, textarea, select');

        fields.forEach(field => {
            if (!validateField(field)) {
                isFormValid = false;
            }
        });

        if (!isFormValid && formConfig.scrollToError) {
            const firstErrorField = form.querySelector(`.${<?php echo json_encode($errorFieldClass); ?>}`);
            if (firstErrorField) {
                firstErrorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstErrorField.focus();
            }
        }

        return isFormValid;
    }

    // 绑定实时验证事件
    if (formConfig.realTimeValidation) {
        const fields = form.querySelectorAll('input, textarea, select');
        
        fields.forEach(field => {
            field.addEventListener('input', () => validateField(field));
            field.addEventListener('blur', () => validateField(field));
            
            if (field.type === 'checkbox') {
                field.addEventListener('change', () => validateField(field));
            }
        });
    }

    // 表单提交处理
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        resetFormState();

        if (!validateForm()) {
            return;
        }

        // 显示加载状态
        if (submitButton) submitButton.disabled = true;
        if (submitText) submitText.textContent = formConfig.submitLoadingText;
        if (loadingIndicator) loadingIndicator.classList.remove('hidden');

        try {
            const formData = new FormData(form);

            const response = await fetch(form.action, {
                method: form.method,
                body: formData,
                headers: {
                    'Accept': 'application/json'
                }
            });

            const result = await response.json();

            if (response.ok && result.success) {
                // 提交成功
                if (successMessage) {
                    successMessage.classList.remove('hidden');
                    // 动态设置成功消息文本
                    successMessage.querySelector('span').textContent = formConfig.successMessage;
                }
                if (formConfig.resetFormAfterSuccess) form.reset();
            } else {
                // 提交失败（服务器返回错误）
                if (errorMessage) {
                    errorMessage.classList.remove('hidden');
                    // 动态设置错误消息文本
                    errorMessageText.textContent = result.message || formConfig.errorMessage;
                }
                
                // 显示服务器返回的字段级错误
                if (result.errors && typeof result.errors === 'object') {
                    Object.keys(result.errors).forEach(fieldName => {
                        const field = form.querySelector(`[name="${fieldName}"]`);
                        if (field) {
                            showFieldError(field, result.errors[fieldName]);
                        }
                    });

                    if (formConfig.scrollToError) {
                        const firstErrorField = form.querySelector(`.${<?php echo json_encode($errorFieldClass); ?>}`);
                        if (firstErrorField) {
                            firstErrorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    }
                }
            }
        } catch (error) {
            // 网络错误处理 - 使用配置的错误消息
            console.error('表单提交错误:', error);
            if (errorMessage) {
                errorMessage.classList.remove('hidden');
                errorMessageText.textContent = formConfig.networkErrorMessage;
            }
        } finally {
            // 恢复表单状态
            if (submitButton) submitButton.disabled = false;
            if (submitText) submitText.textContent = formConfig.submitText;
            if (loadingIndicator) loadingIndicator.classList.add('hidden');
        }
    });
});
</script>
    